package pyf.gaoji;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author pengyifeng
 * @version 5.1
 * @ClassName ManualThreadPool.java
 * @Description 手动创建线程池
 * @createTime 2021年07月27日 17:59:00
 */
public class ManualThreadPool {

    public static final Integer THREAD_POOL_SIZE=16;

    public static void main(String[] args) throws InterruptedException {
        //创建线程工厂
        ThreadFactory factory= new  ThreadFactoryBuilder().setNameFormat("hyn-demo-pool-%d").build();
        //创建线程池
        ThreadPoolExecutor executor= new ThreadPoolExecutor(THREAD_POOL_SIZE,THREAD_POOL_SIZE,0L, TimeUnit.MICROSECONDS,new LinkedBlockingDeque<>(1024),factory, new ThreadPoolExecutor.AbortPolicy());

        //执行
        for (int i = 0; i < 1000; i++) {
            executor.execute(()-> System.out.println(Thread.currentThread().getName()));
        }
        //关闭线程池
        executor.shutdown();
        executor.awaitTermination(1000L, TimeUnit.SECONDS);
        // 任务执行完毕后打印"Done"
        System.out.println("Done");
    }
}
